package com.milkshopbackend.milkshop.controller;

import com.milkshopbackend.milkshop.Service.CartService;
import com.milkshopbackend.milkshop.common.Result;
import com.milkshopbackend.milkshop.entity.Cart;
import com.milkshopbackend.milkshop.entity.CartDTO;
import com.milkshopbackend.milkshop.util.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/api/cart")
@Slf4j
public class CartController {

    @Autowired
    private CartService cartService;

    @PostMapping
    public Result<Void> addToCart(@RequestBody @Valid CartDTO cartDTO) {
        Long userId = SecurityUtils.getCurrentUserId();
        cartService.addToCart(userId, cartDTO);
        return Result.success();
    }

    @GetMapping
    public Result<List<Cart>> getUserCart() {
        Long userId = SecurityUtils.getCurrentUserId();
        List<Cart> cartList = cartService.getCartByUserId(userId);
        return Result.success(cartList);
    }

    @PutMapping("/{cartId}")
    public Result<Void> updateCartItem(@PathVariable Long cartId, @RequestParam Integer quantity) {
        Long userId = SecurityUtils.getCurrentUserId();
        cartService.updateCartItem(userId, cartId, quantity);
        return Result.success();
    }

    @DeleteMapping("/{cartId}")
    public Result<Void> removeCartItem(@PathVariable Long cartId) {
        Long userId = SecurityUtils.getCurrentUserId();
        cartService.removeCartItem(userId, cartId);
        return Result.success();
    }

    @DeleteMapping
    public Result<Void> clearCart() {
        Long userId = SecurityUtils.getCurrentUserId();
        cartService.clearCart(userId);
        return Result.success();
    }
}
